package com.ztools.pc.service.impl.store;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztools.common.model.pc.store.Category;
import com.ztools.common.util.common.PageUtil;
import com.ztools.pc.mapper.store.CategoryMapper;
import com.ztools.pc.service.store.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:一口香菜
 * @Date: 2023/3/26  11:17
 * @Version 1.0
 */
@Transactional
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public Page<Category> findList(PageUtil<Category> pageUtil) {
        List<OrderItem> orders = new ArrayList<>();
        QueryWrapper<Category> queryWrapper = getQueryWrapper(pageUtil.getParams());
        Page<Category> pages = new Page<>(pageUtil.getPage(), pageUtil.getSize());
        // 排序数据  StrUtil.toUnderlineCase huTools将驼峰装换为下划线格式
        orders.add(new OrderItem(StrUtil.toUnderlineCase(pageUtil.getSortName()), "asc".equals(pageUtil.getSortOrder())));
        pages.setOrders(orders);
        return page(pages, queryWrapper);
    }

    @Override
    public boolean delete(Category category) {
        boolean b = false;
        Category userById = getById(category.getId());
        b = removeById(category.getId());
        return b;
    }

    @Override
    public boolean add(Category category) {
        return save(category);
    }

    @Override
    public boolean update(Category category) {
        boolean b = false;
        // 修改前先获取，在删除（乐观锁）
        Category categoryById = getById(category);
        b = updateById(category);
        return b;
    }

    @Override
    public List<Category> findByObject(Category category) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        return list(queryWrapper);
    }


    /**
     * 拼接条件
     *
     * @param category category
     * @return
     */
    public QueryWrapper<Category> getQueryWrapper(Category category) {
        QueryWrapper<Category> gradeQueryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(category.getName())) {
            gradeQueryWrapper.like("name", category.getName());
        }
        return gradeQueryWrapper;
    }

}
